var userManagement_page = {};

userManagement_page.action = {
    initBody: function () {
        userManagement_page.interface.initTablePage();
        userManagement_page.action.bindEvent();
    },
    bindEvent: function () {
        $("#addBtn").click(function () {
            userManagement_page.interface.initPlugins();
            userManagement_page.interface.initFormPage();
            userManagement_page.action.bindEvent();
            return false;
        });
        $("#cancel").click(function () {
            userManagement_page.action.initBody();
            return false;
        });
    },
    bindEventClose:function () {
        $(".close").click(function(){
            this.remove();
        })
    },

    deleteUser: function (userId) {
        var params = {
            id: userId
        };
        var onSuccess = function (resultData) {
            if (resultData.success) {
                layer.msg("删除成功！");
                userManagement_page.data.tableIns.reload();
            }
        };
        AppComm.ajax.execute({
            'url': AppComm.url.getBaseURL() + '/user/ajax/deleteUser',
            'data': params,
            'success': onSuccess
        });
    }
};
userManagement_page.interface = {
    // 加载表格页
    initTablePage: function () {
        var html = template("userManagementList_template");
        $(".userManagement_box").html(html);

        layui.use(['table', 'form'], function () {
            var table = layui.table;

            //执行表格渲染
            var tableIns = table.render({
                height: 550,
                url: AppComm.url.getBaseURL() + '/user/ajax/getUserManagerList',
                elem: "#tb_list",
                page: true,
                limit: 10,
                loading: true,
                id: 'id',
                cols: [[
                    {
                        field: 'fullname',
                        title: '姓名',
                        //width:200,
                        align: 'left'
                    },
                    {
                        field: 'username',
                        title: '账号',
                        align: 'left'
                    }, {
                        field: 'phone',
                        title: '电话',
                        align: 'left'
                    }, {
                        field: 'email',
                        title: '邮箱',
                        align: 'left'
                    }, {
                        field: 'orderId',
                        title: '排序号',
                        edit: 'text',
                        align: 'left'
                    },
                    {
                        field: 'comment',
                        title: '说明',
                        align: 'left'
                    }, {
                        field: 'operation',
                        title: '操作',
                        fixed: 'right',
                        width: 260,
                        toolbar: '#toolbar'
                    }
                ]]
            });

            userManagement_page.data.tableIns = tableIns;

            table.on('tool(tb_list)', function (obj) {
                var rowData = obj.data;
                var layEvent = obj.event;
                if (layEvent === 'editBtn') {
                    userManagement_page.interface.initFormPage(rowData.id);
                    userManagement_page.action.bindEvent();
                    // layer.alert(rowData.id+'ddsdfsdfsdfsdds',{icon: 3, title:'提示'});
                }
                if (layEvent === 'perBtn') {
                    userManagement_page.interface.initPermissionPage(rowData.id);
                    userManagement_page.action.bindEvent();
                }
                if (layEvent === 'deleteBtn') {
                    if(rowData.username=="admin"){
                        layer.msg("管理员账号不能删除！！",{icon: 2});
                    }else{
                        layer.confirm('确定要进行删除吗？', {icon: 3, title: '提示'}, function (index) {
                            userManagement_page.action.deleteUser(rowData.id);
                            layer.close(index);
                        }, function (index) {
                            layer.close(index);
                        });
                    }
                }
                if (layEvent === 'showPer') {

                    var param ={
                        id:rowData.id,
                    };
                    var onSuccess = function (resultData) {
                        if (resultData.success) {
                            var html = template("userManagerList_per", {});
                            var perLayer = layer.open({
                                type: 1,
                                skin: 'layui-layer-rim', //加上边框
                                area: ['800px', '760px'], //宽高
                                offset: '100px',
                                content: html
                            });
                            var myChart = echarts.init(document.getElementById('treePer'));
                            myChart.showLoading();
                            var data1 = {
                                    "name": "菜单",
                                    "children": resultData.data.menu
                                };
                            var data2 = {
                                "name": "操作",
                                "children": resultData.data.permission
                            };
                            myChart.hideLoading();

                            myChart.setOption(option = {
                                tooltip: {
                                    trigger: 'item',
                                    triggerOn: 'mousemove'
                                },
                                legend: {
                                    top: '2%',
                                    left: '3%',
                                    orient: 'vertical',
                                    data: [{
                                        name: '菜单',
                                        icon: 'rectangle'
                                    } ,
                                        {
                                            name: '操作',
                                            icon: 'rectangle'
                                        }],
                                    borderColor: '#c23531'
                                },
                                series:[
                                    {
                                        type: 'tree',

                                        name: '菜单',

                                        data: [data1],

                                        top: '5%',
                                        left: '7%',
                                        bottom: '2%',
                                        right: '60%',

                                        symbolSize: 7,

                                        label: {
                                            normal: {
                                                position: 'left',
                                                verticalAlign: 'middle',
                                                align: 'right'
                                            }
                                        },

                                        leaves: {
                                            label: {
                                                normal: {
                                                    position: 'right',
                                                    verticalAlign: 'middle',
                                                    align: 'left'
                                                }
                                            }
                                        },

                                        expandAndCollapse: true,

                                        animationDuration: 550,
                                        animationDurationUpdate: 750

                                    },
                                    {
                                        type: 'tree',
                                        name: '操作',
                                        data: [data2],

                                        top: '20%',
                                        left: '60%',
                                        bottom: '22%',
                                        right: '18%',

                                        symbolSize: 7,

                                        label: {
                                            normal: {
                                                position: 'left',
                                                verticalAlign: 'middle',
                                                align: 'right'
                                            }
                                        },

                                        leaves: {
                                            label: {
                                                normal: {
                                                    position: 'right',
                                                    verticalAlign: 'middle',
                                                    align: 'left'
                                                }
                                            }
                                        },

                                        expandAndCollapse: true,

                                        animationDuration: 550,
                                        animationDurationUpdate: 750
                                    }
                                ]
                            });
                        }
                    }
                    AppComm.ajax.execute({
                        'url': AppComm.url.getBaseURL() + '/user/ajax/getPermissionListByUserId',
                        'data': param,
                        'success': onSuccess
                    });
                }
            });
            table.on('edit(tb_list)', function(obj){
                var param ={
                    id:obj.data.id,
                    orderId:obj.value,
                }
                var onSuccess = function (resultData) {
                    if (resultData.success) {
                        layer.msg("排序已修改！");
                        userManagement_page.action.initBody();
                    } else {
                        lay.msg("修改失败！");
                    }
                };
                AppComm.ajax.execute({
                    'url': AppComm.url.getBaseURL() + '/user/ajax/saveUser',
                    'data': param,
                    'success': onSuccess
                });
            });
            // 查询
            var form = layui.form;
            form.render(null, 'searchForm');
            form.on('submit(searchBtn)', function (data) {
                var postData = {
                    fullname: data.field.fullnameInput
                };
                tableIns.reload({
                    where: postData
                });
                return false;
            });
        });

    },
    // 初始化表单页
    initFormPage: function (dataId) {
        if (dataId == undefined || '' == dataId.trim()) {
            // 添加
            var html = template("userManagementForm_template");
            $(".userManagement_box").html(html);
            userManagement_page.action.bindEvent();
            layui.use('form', function(){
                var form = layui.form;
                form.verify({
                    username:function(value){
                        if(value==""||value==null){
                            return "账号不能为空";
                        }
                        var flag = 0;
                        var params={
                            userName:value,
                        };
                        var onSuccess = function (resultData) {
                            if (resultData.success) {
                                if(resultData.data!=null){
                                    flag++;
                                }
                            }
                        };
                        AppComm.ajax.execute({
                            'url':AppComm.url.getBaseURL()+'/user/ajax/getUserByUserName',
                            'data':params,
                            'async':false,
                            'success':onSuccess
                        });
                        if(flag>0){
                            return "角色关键字已存在";
                        }
                    },
                });

                form.on('submit(submitBtn)', function(data){
                    data.field.fileJson = JSON.stringify(userManagement_page.data.imgUpload.getSingleUploadFile());
                    var onSuccess = function (resultData) {
                        if (resultData.success) {
                            layer.msg("保存成功！");
                            userManagement_page.action.initBody();
                        } else {
                            lay.msg("保存失败！");
                        }
                    };
                    AppComm.ajax.execute({
                        'url': AppComm.url.getBaseURL() + '/user/ajax/saveUser',
                        'data': data.field,
                        'success': onSuccess
                    });
                });
            });
            //添加页面显示默认的图片
            $("#test_imgUpload2Preview").attr("src",AppComm.url.getBaseURL() +"/static/comm/img/defaultHead.jpg");
        } else {
            // 编辑
            layer.load();
            var params = {
                id: dataId
            };
            var onSuccess = function (resultData) {
                layer.closeAll('loading');
                //获取上传头像的url
                var imgUrl = null;
                if(resultData.data.unitFile != null){
                    imgUrl = resultData.data.unitFile.sourceUrl;
                }
                var html = template("userManagementForm_template", resultData.data);
                $(".userManagement_box").html(html);
                userManagement_page.interface.initPlugins();
                //判断头像是否已经上传
                if(imgUrl == null || imgUrl == ""){
                    $("#test_imgUpload2Preview").attr("src",AppComm.url.getBaseURL()+"/static/comm/img/defaultHead.jpg");
                }
                userManagement_page.action.bindEvent();
                $("#username_div").remove();
                $("#pswd_div").remove();
                layui.use('form', function(){
                    var form = layui.form;
                    form.verify({
                        username:function(value){
                            var flag = 0;
                            var params={
                                id:resultData.data.id,
                                userName:value,
                            };
                            var onSuccess = function (resultData) {
                                if (resultData.success) {
                                    if(resultData.data!=null){
                                        flag++;
                                    }
                                }
                            };
                            AppComm.ajax.execute({
                                'url':AppComm.url.getBaseURL()+'/user/ajax/getUserByUserNameOutCurrent',
                                'data':params,
                                'async':false,
                                'success':onSuccess
                            });
                            if(flag>0){
                                return "用户名已存在";
                            }
                        },
                    });

                    form.on('submit(submitBtn)', function(data){
                        data.field.id=dataId;
                        data.field.fileJson = JSON.stringify(userManagement_page.data.imgUpload.getSingleUploadFile());
                        var onSuccess = function (resultData) {
                            if (resultData.success) {
                                layer.msg("保存成功！");
                                userManagement_page.action.initBody();
                            } else {
                                lay.msg("保存失败！");
                            }
                        };
                        AppComm.ajax.execute({
                            'url': AppComm.url.getBaseURL() + '/user/ajax/saveUser',
                            'data': data.field,
                            'success': onSuccess
                        });
                    });
                });
            };
            AppComm.ajax.execute({
                'url': AppComm.url.getBaseURL() + '/user/ajax/getUserById',
                'data': params,
                'success': onSuccess
            });
        }
    },
    //角色授权界面初始化
    initPermissionPage: function (dataId) {
        var existParams={
            id:dataId
        }
        var html = template("userManagerList_role", {});
        var roleLayer = layer.open({
            type: 1,
            skin: 'layui-layer-rim', //加上边框
            area: '720px', //宽高
            offset: '100px',
            content: html
        });
        var onSuccessExist = function (resultData) {
            console.log(resultData.data);
            if (resultData.success) {
                for(var i=0;i<resultData.data.length;i++){
                    var roLog = "<button class='close' style='margin:3px;display: inline-block;height: 38px;line-height: 38px;padding: 0 18px;border: 1px solid #C9C9C9;background-color: #fff;color: #555;white-space: nowrap;text-align: center;font-size: 14px;border-radius: 2px;cursor: pointer; -moz-user-select: none; -webkit-user-select: none;'"+"data_id="+resultData.data[i].id+">"+resultData.data[i].roleName+"<span class='layui-badge' >x</span></button>"
                    $("#roLog").append(roLog);
                    userManagement_page.action.bindEventClose();
                }
            }
        }
        AppComm.ajax.execute({
            'url':AppComm.url.getBaseURL()+'/role/ajax/getRolesByUserId',
            'data':existParams,
            'success':onSuccessExist
        });
            layui.use(['table', 'form'], function () {
                var table = layui.table;
                    //执行表格渲染
                    var roleTable = table.render({
                        elem: "#ro_list",
                        url: AppComm.url.getBaseURL()+'/role/ajax/getRoleManagerList',
                        page: {
                            layout: ['count', 'prev', 'page', 'next', 'skip']
                        },
                        limit: 10,
                        heigth:"600px",
                        loading: true,
                        id: 'ro_list',
                        cols: [[
                            {
                                field: 'roleName',
                                title: '角色名称',
                                width: 200,
                                align: 'left',
                                event: 'setSign',
                            },
                            {
                                field: 'roleKey',
                                title: '角色关键字',
                                width: 200,
                                align: 'left',
                                event: 'setSign',
                            },
                             {
                                field: 'comment',
                                title: '角色说明',
                                width: 200,
                                align: 'left',
                                event: 'setSign',
                            }
                        ]]
                    });


                table.on('tool(ro_list)', function (obj) {
                    var rowData = obj.data;
                    var layEvent = obj.event;
                    if(obj.event === 'setSign'){
                        var flag=0;
                        $("#roLog button").each(function(index,item) {
                            if($(item).attr("data_id")==rowData.id){
                                flag++
                            }
                        })
                        if(flag==0){
                            var roLog = "<button class='close' style='margin:3px;display: inline-block;height: 38px;line-height: 38px;padding: 0 18px;border: 1px solid #C9C9C9;background-color: #fff;color: #555;white-space: nowrap;text-align: center;font-size: 14px;border-radius: 2px;cursor: pointer; -moz-user-select: none; -webkit-user-select: none;'"+"data_id="+rowData.id+">"+rowData.roleName+"<span class='layui-badge' >x</span></button>"
                            $("#roLog").append(roLog);
                            userManagement_page.action.bindEventClose();
                        }
                        if(flag>0){
                            layer.msg('不能重复添加', {
                                time: 2000, //2s后自动关闭
                            });
                        }
                    }
                });
                // 查询
                var form = layui.form;
                form.render(null, 'searchRoleForm');
                form.on('submit(searchRole)', function (data) {
                    var postData = {
                        roleName: data.field.roleName
                    };
                    roleTable.reload({
                        where: postData
                    });
                    return false;
                });
                $("#getCheckData").click(function () {
                    var roleD = new Array();
                    $("#roLog button").each(function(index,item) {
                        roleD.push($(item).attr("data_id"));
                    })
                    var ids = roleD.join(",");
                    var params= {
                        id:dataId,
                        ids:ids
                    }
                    var onSuccess1 = function (resultData) {
                        if (resultData.success) {
                            layer.close(roleLayer);
                            layer.msg("配置成功！");
                        }
                    };
                    AppComm.ajax.execute({
                        'url':AppComm.url.getBaseURL()+'/role/ajax/saveRolePer',
                        'data':params,
                        'success':onSuccess1
                    });
                    return false;
                });
            });

    },
// 初始化相关插件
    initPlugins: function(){
        //初始化图片上传插件
        var imgUpload = new CommonImageUpload("test_imgUpload2");
        userManagement_page.data.imgUpload = imgUpload;
        imgUpload.singleImageUploadInit(null);

    },
}

userManagement_page.data = {
    'tableIns': undefined,
    roleTable:null,
    imgUpload:null
};

userManagement_page.event = {
    'isReaded': false,
    onReady: function () {
        userManagement_page.action.initBody();
    }
};

AppComm.action.ready(function () {
    if (!userManagement_page.event.isReaded) {
        userManagement_page.event.isReaded = true;
        userManagement_page.event.onReady();
    }
});